package distriKub;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Timer extends Thread{
	
	private int numOfTicks = 0;
	private int timeSecond = 1000; // Milliseconds
	private String timerName;
	
	private boolean threadDone = false;

	// Start of making Timer an event generator
	private List<TimeListener> _listeners = new ArrayList<TimeListener>();

	public synchronized void addTimeListener(TimeListener l) {
		_listeners.add(l);
	} // End of addTimeListener

	public synchronized void removeTimeListener(TimeListener l) {
		_listeners.remove(l);
	} // End of removeTimeListener

	private synchronized void _fireTimeEvent(int time){
		TimeEvent timeEvent = new TimeEvent(this, time);
		Iterator<TimeListener> listeners = _listeners.iterator();
		while (listeners.hasNext()) {
			((TimeListener) listeners.next()).timeTick(timeEvent);
		} // End of while block
	} // End of _fireComEvent
		// End of making Timer an event generator
	
	public synchronized void resetTimer() {
		numOfTicks = 0;
	}
	
	public void stopTimer(){
		threadDone = true;
	}
	
	public void setTimerName(String theName){
		this.timerName = theName;
	}
	
	public String getTimerName(){
		return this.timerName;
	}

	public void run() {
		while (!threadDone){
		try{Thread.sleep(timeSecond-100); wait(100);}catch (Exception E){/* Do nothing */}
		numOfTicks++;
		_fireTimeEvent(numOfTicks);
		}// End of while loop
	} // End of run method
	
}